const express = require("express");
const multer = require("multer");
const FileModel = require("../models/file");
const router = express.Router();
const upload = multer({
  dest: "uploads",
  fileFilter: (req, file, callback) => {
    const mimetypes = ["image/png", "image/jpg", "image/jpeg"];

    const allowed = mimetypes.some(type => type === file.mimetype);

    if (allowed) {
      callback(null, true);
    } else {
      callback(new Error("不支持上传此类型的文件。"), false);
    }
  }
});

// 文件上传动作
router.post("/", upload.single("file"), async (req, res) => {
  const file = new FileModel(req.file);
  await file.save();
  res.send({
    code: 0,
    msg: "ok",
    data: {
      ...file.toJSON(),
      url: `/files/serve/${file._id}`
    }
  });
});

// 文件服务
router.get("/serve/:id", async (req, res) => {
  const file = await FileModel.findById(req.params.id);
  console.log(file);
  res.sendFile(file.filename, {
    root: "./uploads",
    headers: {
      "Content-type": file.mimetype
    }
  });
});

module.exports = router;
